package cn.wolfcode.shop.controller;


import cn.wolfcode.shop.domain.UserLogin;
import cn.wolfcode.shop.exception.UserException;
import cn.wolfcode.shop.service.IUserLoginService;
import cn.wolfcode.shop.vo.JSONResultVo;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/users")
public class UserLoginController {
    @Reference
    private IUserLoginService userLoginService;

    /**
     * 用户注册
     * 路径:/api/users/
     * 方法:POST
     * 状态码:201
     */
    @PostMapping
    public JSONResultVo register(String username, String password, HttpServletResponse response){
        JSONResultVo vo = new JSONResultVo();
        try {
            UserLogin userLogin = userLoginService.register(username, password);
            vo.setResult(userLogin);
            response.setStatus(HttpServletResponse.SC_CREATED);
        } catch (UserException e){
            e.printStackTrace();
            vo.setErrorMsg(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        return vo;
    }

    /**
     * 用户登录
     * 路径:/api/users/tokens
     * 方法:POST
     * 状态码:201
     */
    @PostMapping(value = "/tokens")
    public JSONResultVo login(String username, String password, HttpServletResponse response){
        JSONResultVo vo = new JSONResultVo();
        try {
            String token = userLoginService.login(username, password);
            vo.setResult(token);
            response.setStatus(HttpServletResponse.SC_CREATED);
        } catch (UserException e){
            e.printStackTrace();
            vo.setErrorMsg(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        return vo;
    }

    /**
     * 用户登出
     * 路径:/api/users/tokens/token
     * 方法:DELETE
     * 状态码:204
     */
    @DeleteMapping(value = "/tokens/{token}")
    public JSONResultVo logout(@PathVariable("token") String token, HttpServletResponse response){
        JSONResultVo vo = new JSONResultVo();
        try {
            userLoginService.logout(token);
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } catch (UserException e){
            e.printStackTrace();
            vo.setErrorMsg(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        return vo;
    }

}
